from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from .models import PointTransaction, RewardItem
from backed.pagination import get_pagination_params, paginate_queryset
from users.models import UserProfile
from django.db import transaction
from .utils import award_points


@csrf_exempt
@login_required
@require_http_methods(["GET"])
def points_view(request):
    try:
        profile, _ = UserProfile.objects.get_or_create(user=request.user)
        return JsonResponse({'success': True, 'data': {'points': profile.points}}, status=200)
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)}, status=500)


@csrf_exempt
@login_required
@require_http_methods(["GET"])
def transactions_view(request):
    try:
        qs = PointTransaction.objects.filter(user=request.user).order_by('-created_at')
        page = int(request.GET.get('page') or 1)
        page_size = int(request.GET.get('page_size') or 10)
        total = qs.count()
        start = (page - 1) * page_size
        end = start + page_size
        items = [{
            'transaction_id': t.transaction_id,
            'points': t.points,
            'action_type': t.action_type,
            'related_id': t.related_id,
            'created_at': t.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for t in qs[start:end]]
        return JsonResponse({'success': True, 'data': {'items': items, 'meta': {'page': page, 'page_size': page_size, 'total': total}}})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)}, status=500)


@csrf_exempt
@require_http_methods(["GET"])
def shop_view(request):
    try:
        qs = RewardItem.objects.all().order_by('item_id')
        page, page_size = get_pagination_params(request, default_page_size=10, max_page_size=100)
        page_qs, meta = paginate_queryset(qs, page, page_size)
        items = [{
            'item_id': i.item_id,
            'name': i.name,
            'points_cost': i.points_cost,
            'description': i.description,
            'stock': i.stock
        } for i in page_qs]
        return JsonResponse({'success': True, 'data': {'items': items, 'meta': meta}})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)}, status=500)


@csrf_exempt
@login_required
@require_http_methods(["POST"])
def redeem_view(request):
    try:
        data = request.POST if request.content_type != 'application/json' else __import__('json').loads(request.body or '{}')
        item_id = data.get('item_id')
        if not item_id:
            return JsonResponse({'success': False, 'message': '缺少item_id'}, status=400)
        try:
            item = RewardItem.objects.get(item_id=item_id)
        except RewardItem.DoesNotExist:
            return JsonResponse({'success': False, 'message': '商品不存在'}, status=404)
        with transaction.atomic():
            profile, _ = UserProfile.objects.get_or_create(user=request.user)
            if profile.points < item.points_cost:
                return JsonResponse({'success': False, 'message': '积分不足'}, status=400)
            profile.points -= item.points_cost
            profile.save()
            PointTransaction.objects.create(user=request.user, points=-item.points_cost, action_type='redeem', related_id=item.item_id)
            if item.stock > 0:
                item.stock -= 1
                item.save()
        return JsonResponse({'success': True, 'message': '兑换成功', 'data': {'item_id': item.item_id}}, status=201)
    except __import__('json').JSONDecodeError:
        return JsonResponse({'success': False, 'message': '无效的JSON'}, status=400)
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)}, status=500)

# Create your views here.
